package net.vanchu.mortgagecalculator.common.commonView.component;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dtspread.apps.houseloan.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: wangjie
 * Email: tiantian.china.2@gmail.com
 * Date: 7/1/14.
 */
public class WheelView extends ScrollView {

    public static final String TAG = WheelView.class.getSimpleName();

    public static final int OFF_SET_DEFAULT = 1;

    private int selectedIndex = 1;
    private int initialY;
    private int checkDelay = 50;

    private static final int fontSizeAccent = 20;
    private static final int fontSizeSecondary = 16;

    private int colorAccent;
    private int colorSecondary;
    private int colorThird;
    private int colorForth;

    private Paint paint;
    private int viewWidth;
    private int viewHeight;

    private LinearLayout viewsContainer;

    private Runnable scrollerTask;

    private int offset = OFF_SET_DEFAULT; // 偏移量（需要在最前面和最后面补全）

    public void setOffset(int offset) {
        this.offset = offset;
    }

    private List<String> items = new ArrayList<>();

    private static final String EMPTY_ITEM = "";

    public void setItems(List<String> list) {
        items.clear();
        items.addAll(list);
        // 前面和后面补全
        for (int i = 0; i < offset; i++) {
            items.add(0, EMPTY_ITEM);
            items.add(EMPTY_ITEM);
        }
        for (String item : items) {
            viewsContainer.addView(createView(item));
        }
        measureViewSize();
        refreshItemView(0);
        invalidate();
    }

    public WheelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        colorAccent = getResources().getColor(R.color.txt_wheel_view_selected);
        colorSecondary = getResources().getColor(R.color.txt_wheel_view_secondary);
        colorThird = getResources().getColor(R.color.txt_wheel_view_third);
        colorForth = getResources().getColor(R.color.txt_wheel_view_forth);

        viewsContainer = new LinearLayout(context);
        viewsContainer.setOrientation(LinearLayout.VERTICAL);
        this.addView(viewsContainer);
        this.setVerticalScrollBarEnabled(false);

        initScrollTask();
        assiginSelectPosition();
    }

    public void startScrollerTask() {
        initialY = getScrollY();
        this.postDelayed(scrollerTask, checkDelay);
    }

    int itemHeight = 0; // 非居中的 item 的高度

    int accentItemHeight = 0; // 居中的 item 的高度

    private TextView createView(String item) {
        TextView tv = getTextView();
        tv.setText(item);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        return tv;
    }

    private void measureViewSize() {
        TextView tv = getTextView();
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        if (itemHeight == 0 && accentItemHeight == 0) {
            for (String item : items) {
                if (item.length() == 0) {
                    continue;
                }
                tv.setText(item);
                // 测量普通的文本高度
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                itemHeight = getViewMeasuredHeight(tv);
                // 测量居中的文本的高度
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                accentItemHeight = getViewMeasuredHeight(tv);
            }
        }

        // 整个 view 的高度 = 普通文本高度 * offset * 2 + 居中文本高度
        viewHeight = itemHeight * offset * 2 + accentItemHeight;
        // 子 View 的布局参数
        viewsContainer.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, viewHeight));
        // ScrollView 的布局参数
        this.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, viewHeight));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    }

    @NonNull
    private TextView getTextView() {
        TextView tv = new TextView(getContext());
        tv.setSingleLine(true);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(0, dip2px(8), 0, dip2px(10));
        tv.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        return tv;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        refreshItemView(t);
    }

    private void refreshItemView(int y) {
        int center = y / itemHeight + offset;
        int remainder = y % itemHeight;
        int divided = y / itemHeight;

        if (remainder == 0) {
            center = divided + offset;
        } else {
            if (remainder > itemHeight / 2) {
                center = divided + offset + 1;
            }
        }

        int childSize = viewsContainer.getChildCount();
        for (int i = 0; i < childSize; i++) {
            TextView itemView = (TextView) viewsContainer.getChildAt(i);
            if (null == itemView) {
                return;
            }
            if (i == center) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorAccent);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeAccent);
            } else if (i == center - 3) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorForth);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            } else if (i == center - 2) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorThird);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            } else if (i == center - 1) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorSecondary);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            } else if (i == center + 1) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorSecondary);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            } else if (i == center + 2) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorThird);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            } else if (i == center + 3) {
                itemView.setText(items.get(i));
                itemView.setTextColor(colorForth);
                itemView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSecondary);
            }
        }
    }

    /**
     * 选中回调
     */
    private void assiginSelectPosition() {
        if (null != onItemSelectListener) {
            onItemSelectListener.onSelected(selectedIndex, items.get(selectedIndex));
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setBackgroundDrawable(null);
    }

    public void setSelection(final int position) {
        selectedIndex = position + offset;
        assiginSelectPosition();
        this.post(new Runnable() {
            @Override
            public void run() {
                WheelView.this.smoothScrollTo(0, position * itemHeight);
            }
        });
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 3);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            startScrollerTask();
        }
        return super.onTouchEvent(ev);
    }

    private int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int getViewMeasuredHeight(View view) {
        int width = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        view.measure(width, expandSpec);
        return view.getMeasuredHeight();
    }

    private OnItemSelectListener onItemSelectListener;

    public void setOnItemSelectListener(OnItemSelectListener onItemSelectListener) {
        this.onItemSelectListener = onItemSelectListener;
    }

    public interface OnItemSelectListener {
        void onSelected(int selectedIndex, String item);
    }

    @Override
    public void setBackgroundDrawable(Drawable background) {
        if (null == paint) {
            paint = new Paint();
            paint.setColor(getResources().getColor(R.color.divide_wheel_view));
            paint.setStrokeWidth(dip2px(1f));
        }

        background = new Drawable() {
            @Override
            public void draw(Canvas canvas) {
                canvas.drawLine(0,
                        itemHeight * 3,
                        viewWidth,
                        itemHeight * 3,
                        paint);
                canvas.drawLine(0,
                        itemHeight * 3 + accentItemHeight,
                        viewWidth,
                        itemHeight * 3 + accentItemHeight,
                        paint);
            }

            @Override
            public void setAlpha(int alpha) {

            }

            @Override
            public void setColorFilter(ColorFilter cf) {

            }

            @Override
            public int getOpacity() {
                return 0;
            }
        };
        super.setBackgroundDrawable(background);
    }

    private void initScrollTask() {
        scrollerTask = new Runnable() {
            public void run() {
                int newY = getScrollY();

                // 滑动中，每隔 50ms 检查一次
                if (initialY != newY) {
                    initialY = getScrollY();
                    WheelView.this.postDelayed(scrollerTask, checkDelay);
                    return;
                }
                // 停止滑动
                final int remainder = initialY % itemHeight;
                final int divided = initialY / itemHeight;
                // 移动距离 = item 高度的整数倍
                if (remainder == 0) {
                    selectedIndex = divided + offset;
                    assiginSelectPosition();
                    return;
                }
                // 移动距离 != item 高度的整数倍
                if (remainder > itemHeight / 2) {
                    WheelView.this.post(new Runnable() {
                        @Override
                        public void run() {
                            WheelView.this.smoothScrollTo(0, initialY - remainder + itemHeight);
                            selectedIndex = divided + offset + 1;
                            assiginSelectPosition();
                        }
                    });
                } else {
                    WheelView.this.post(new Runnable() {
                        @Override
                        public void run() {
                            WheelView.this.smoothScrollTo(0, initialY - remainder);
                            selectedIndex = divided + offset;
                            assiginSelectPosition();
                        }
                    });
                }
            }
        };
    }

    public interface SingleWvCallBack<T> {
        void onSelected(T t);
    }

    public interface TwoWvCallBack<L, R> {
        void onSelected(L l, R r);
    }
}